#include <string.h>
#include <stdio.h>
#include <numa.h>
#include <pthread.h>
#include <stdlib.h>
#include "param.h"
#include "types.h"

extern int numa_opt;
/* 分配成功返回pool指针，反之NULL */
mempool*
mempool_init (mempool* pool, uint64 buf_num, uint64 buf_siz) {
    uint64 i;
    pool->buf_num = buf_num;
    pool->bufs = (membuf *) malloc (sizeof (membuf)* buf_num);
    if (pool->bufs == NULL) {
        fprintf (stderr, "Memory pool : Insufficient memory.\n");
        return NULL;
    }
    for (i = 0; i < buf_num; i++) {
        pool->bufs[i].size = buf_siz;
        if (numa_opt) {
            pool->bufs[i].buf = numa_alloc_onnode (buf_siz, i % NUMA_NODES);
            pool->bufs[i].numa_id = i % NUMA_NODES;
        } else {
            pool->bufs[i].buf = malloc (buf_siz);
            pool->bufs[i].numa_id = i % NUMA_NODES;
        }
        if (pool->bufs[i].buf == NULL) {
            perror ("Unable to allocate memory");
            fprintf (stderr, "Memory pool : Insufficient memory.\n");
            return NULL;
        }
        pool->bufs[i].stat = B_UNUSED;
        pthread_mutex_init(&(pool->bufs[i].mtx), NULL);
    }
    return pool;
}
